package com.cws.backup.config;

import com.cws.backup.entity.BackupEntity;
import com.cws.backup.properties.BackupProperties;
import com.cws.backup.thread.BackupThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;

/**
 * @author cws
 */
@Slf4j
@Configuration
@EnableScheduling
public class AutoBackupTaskConfig implements SchedulingConfigurer {
    @Autowired
    BackupProperties backupProperties;
    @Autowired
    @Qualifier(value = "crawlExecutorPool")
    private ExecutorService pool;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List<BackupEntity> backupTaskList = backupProperties.getTaskList();
        for (BackupEntity backupEntity : backupTaskList) {
            //是否启用
            if (Objects.equals(backupEntity.getEnable(), "Y")) {
                String cron = backupEntity.getCron();
                BackupThread backupThread = new BackupThread(backupEntity);
                //是否程序启动时运行
                if (Objects.equals(backupEntity.getRunAtStartUp(), "Y")) {
                    log.info("{}启动时运行..", backupEntity);
                    backupThread.run();
                }
                //注册定时任务
                CronTask cronTask = new CronTask(backupThread, cron);
                taskRegistrar.addCronTask(cronTask);
                taskRegistrar.setScheduler(pool);
            }
        }
    }
}
